package com.transaction.demo.shop.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.annotation.Resource;

public class TransactionSynchronizationExample {

    @Resource
    private PlatformTransactionManager transactionManager;

    public TransactionSynchronizationExample(PlatformTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    public void doTransactionalWork() {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setName("exampleTransaction");
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

        TransactionStatus status = transactionManager.getTransaction(def);

        try {
            // 你的业务逻辑
            System.out.println("Doing transactional work...");

            // 注册事务同步回调
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                @Override
                public void beforeCommit(boolean readOnly) {
                    System.out.println("Before commit");
                }

                @Override
                public void afterCommit() {
                    System.out.println("After commit");
                }

                @Override
                public void beforeCompletion() {
                    System.out.println("Before completion");
                }

                @Override
                public void afterCompletion(int status) {
                    if (status == TransactionSynchronization.STATUS_COMMITTED) {
                        System.out.println("Transaction committed");
                    } else if (status == TransactionSynchronization.STATUS_ROLLED_BACK) {
                        System.out.println("Transaction rolled back");
                    }
                }
            });

            // 模拟异常以触发回滚
            // if (true) throw new RuntimeException("Simulated exception");

            transactionManager.commit(status);
        } catch (Exception ex) {
            transactionManager.rollback(status);
            throw ex;
        }
    }

    public static void main(String[] args) {
        // 配置数据源和事务管理器
        // 这里使用了一个假设的配置，请根据实际情况修改
        PlatformTransactionManager transactionManager = null; // 请替换为实际的事务管理器

        TransactionSynchronizationExample example = new TransactionSynchronizationExample(transactionManager);
        example.doTransactionalWork();
    }
}
